<script lang="ts" setup>
  import { TableOptions } from '@/types/dataTable'
  import { useParamsListQuery } from '@/hooks/paramsListQuery'
  import { useStatusTag } from '@/views/competition/hooks/useStatusTag'
  import { useSettingStore } from '@/store/modules/setting'
  import { Bell, Search, Delete, Edit, Plus } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import PdfViewer from '@/components/PdfViewer/index.vue'
  import { useUserStore } from '@/store/modules/user'
  import { getFullSignature, getHeadSignature, getSignature } from '@/api/upload'

  const { listQuery } = useParamsListQuery()
  const settingStore = useSettingStore()
  // 获取用户store
  const userStore = useUserStore()
  const userName = userStore.userInfo?.name || userStore.userInfo?.employeeNumber || '主动生成'
  const userId = userStore.userInfo?.id || 'CDTUXXXX'
  // 获取模式状态
  const isDark = computed(() => settingStore.themeConfig.isDark)
  defineOptions({
    name: 'MyCompetition',
  })
  const options = ref<TableOptions>({
    add: {
      enable: false,
      permission: '',
    },
    edit: {
      enable: false,
      permission: '',
    },
    delete: {
      enable: false,
      permission: '',
      url: '/dict/deleteDicData',
    },
    addRoute: 'addCompetition',
    listUrl: '/competition/pageQuery',
  })

  // 查看附件
  const dialogFormVisible = ref(false)
  const pdfData = ref({
    cosUrl: '',
    cosHeadUrl: '',
    key: '', // 用于强制重新渲染PDF组件
  })
  const signedWordUrl = ref('') // 签名后的Word文件URL
  const wordViewerRef = ref<any>(null) // Word预览组件引用
  const lookFile = async (url: string, id: string) => {
    try {
      // 并行获取签名URL
      const [cosUrl, cosHeadUrl] = await Promise.all([
        getSignature({ value: userName + userId, key: url }),
        getHeadSignature({ value: userName + userId, key: url }),
      ])
      const fileExtension = url.split('.').pop()
      if (fileExtension === 'docx') {
        signedWordUrl.value = cosUrl
        wordViewerRef.value?.openDialog(signedWordUrl.value, '竞赛附件信息预览', '60%')
        return
      } else if (fileExtension === 'pdf') {
        // 一次性更新PDF数据（减少响应式更新次数）
        pdfData.value = {
          cosUrl,
          cosHeadUrl,
          key: id, // 使用时间戳作为key强制重新渲染
        }
        dialogFormVisible.value = true
        return
      } else if (fileExtension === 'zip') {
        open(cosUrl)
        return
      }
    } catch (error) {
      console.error('获取PDF签名失败:', error)
      ElMessage.error('加载PDF失败，请稍后重试')
      dialogFormVisible.value = false
    }
  }
  const open = (url: string) => {
    ElMessageBox.confirm('当前附件为zip压缩包，暂不支持在线预览，请下载后查看', '提示', {
      confirmButtonText: '下载',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      const link = document.createElement('a')
      link.href = url
      link.download = '' // 可以指定下载文件名，不写则使用服务器返回的
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage({
        type: 'success',
        message: '开始下载',
      })
    })
  }
  // 预览word
  const wordPreview = async (url: string) => {
    signedWordUrl.value = await getSignature({ value: userName + userId, key: url })
    wordViewerRef.value?.openDialog(signedWordUrl.value, '竞赛申请表预览', '60%')
  }
</script>
<template>
  <div class="app-container">
    <data-table ref="pagingTable" :options="options" :list-query="listQuery">
      <template #filter-content>
        <el-input
          id="search-keyword"
          v-model.trim="listQuery.params.keyword"
          :prefix-icon="Search"
          style="width: 200px"
          placeholder="竞赛名称"
          class="filter-item"
        />
      </template>
      <template #data-columns>
        <el-table-column align="center" show-overflow-tooltip prop="name" label="竞赛名称" />
        <el-table-column align="center" show-overflow-tooltip prop="contact" width="120" label="负责人" />
        <el-table-column align="center" label="申请状态" width="160">
          <template #default="scope">
            <component :is="useStatusTag(scope.row.applicationStatus, scope.row.isPublished)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="比赛时间" width="240">
          <template #default="scope"> {{ scope.row.startTime }} ~ {{ scope.row.endTime }} </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="申请时间" width="180" />
        <el-table-column align="center" label="申请表" width="110">
          <template #default="scope">
            <el-button
              size="small"
              color="#626aef"
              :dark="isDark"
              plain
              type="primary"
              :icon="Search"
              @click="wordPreview(scope.row.fileList)"
              >预览</el-button
            >
          </template>
        </el-table-column>
        <el-table-column align="center" prop="fileLists" label="附件信息">
          <template #default="scope">
            <el-tag v-for="(value, index) in scope.row.fileLists" type="warning" @click="lookFile(value.url, value.id)">{{
              '附件' + (index + 1)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button type="primary" size="small">查看</el-button>
          </template>
        </el-table-column>
      </template>
    </data-table>
  </div>
  <!-- 弹框 -->
  <el-dialog v-model="dialogFormVisible" top="5vh" height="70vh" width="60%" class="pdf-dialog">
    <div class="pdf-container">
      <PdfViewer :key="pdfData.key" :pdf-url="pdfData.cosUrl" :head-url="pdfData.cosHeadUrl" :chunk-size="1024 * 1024 * 5" />
    </div>
  </el-dialog>
  <WordViewer ref="wordViewerRef" />
</template>

<style scoped>
  .pdf-dialog :deep(.el-dialog__body) {
    height: 80vh;
    padding: 0;
    overflow: hidden;
  }

  .pdf-container {
    height: 100%;
    width: 100%;
    overflow: auto;
  }

  .pdf-container :deep(.pdf-viewer) {
    height: 100%;
  }

  .pdf-container :deep(.pdf-pages) {
    overflow: auto;
  }
</style>
